package server

import (
	"net/http"
	"sync"

	"starsine.cn/appTpl/cmn/config/aconf"
	. "starsine.cn/appTpl/cmn/defs"
	"starsine.cn/appTpl/cmn/logs"
	"starsine.cn/appTpl/svclog/src/fe/openapi"
)

type ApiServer struct {
	sync.Once
	appCtxt *AppContext
	scAddr  string
}

func CreateApiServer(appCtxt *AppContext) (*ApiServer, error) {
	p := new(ApiServer)
	p.appCtxt = appCtxt
	p.scAddr = aconf.GetString("FrontEnd.Addr", "0.0.0.0:20103", aconf.WithENV("fe_addr"))

	p.Start()

	return p, nil
}

func (p *ApiServer) Start() {
	logs.Infof("registry.ApiServer start")

	AuthoApiService := NewAuthoApiService()
	AuthoApiController := NewAuthoApiController(AuthoApiService)

	WebsocketApiService := NewWebsocketApiService()
	WebsocketApiController := NewWebsocketApiController(WebsocketApiService)

	router := openapi.NewRouter(AuthoApiController, WebsocketApiController)

	p.Once.Do(func() {
		go func() {
			logs.Infof("registry.ApiServer listen at: %s", p.scAddr)
			http.ListenAndServe(p.scAddr, router)
		}()
	})
}
